package com.goudan.demo.util;

import com.goudan.demo.common.errorCode.BizException;
import com.goudan.demo.common.errorCode.CommonErrorCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.StringJoiner;

/**
 * 根据validation-api 手动参数校验工具类
 */
@Slf4j
public class ValidationUtil {

    private static final ValidatorFactory factory = Validation.buildDefaultValidatorFactory();

    /**
     * javax.validation注解校验，分组校验
     * 注：分组校验时，仅校验了注解中带有分组的属性，如果想连带着校验默认属性，请加上【Default.class】
     *
     * @param t      校验实体
     * @param groups 校验分组
     */
    public static <T> void validate(T t, Class<?>... groups) {
        Validator validator = factory.getValidator();
        Set<ConstraintViolation<T>> resultSet;
        if (groups != null && groups.length > 0) {
            resultSet = validator.validate(t, groups);
        } else {
            resultSet = validator.validate(t);
        }
        dealResultSet(resultSet);
    }

    /**
     * 处理校验结果——>校验失败，抛出异常
     *
     * @param resultSet 校验结果
     */
    private static <T> void dealResultSet(Set<ConstraintViolation<T>> resultSet) {
        StringJoiner errMsg = new StringJoiner(",", "参数校验失败:", "->请重新传参！");
        if (!CollectionUtils.isEmpty(resultSet)) {
            resultSet.forEach(e -> errMsg.add(e.getMessage()));
            log.info("ValidationUtil校验参数失败");
            throw new BizException(CommonErrorCode.INVALID_REQUEST_PARAM_ERROR.code(), errMsg.toString());
        }
    }


}
